package com.lagou.service;

import com.lagou.boot.ServerBoot;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Service;

/**
 * @author czq
 * @date 2020/8/10 19:25
 */
@Service
public class UserServiceImpl implements IUserService {

    private static final String INIT = "init";

    /**
     * 将来客户端要远程调用的方法
     * @param msg
     * @return
     */
    @Override
    public String sayHello(String msg) {
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        String childrenPath = "/lg-ZkClient/" + ServerBoot.IP + "_" + ServerBoot.PORT;
        long currentTime = System.currentTimeMillis();

        Object o = zkClient.readData(childrenPath);
        System.out.println("当前访问的子节点是：" + childrenPath);
        System.out.println("上一次响应时间：" + o);

        if (INIT.equals(o.toString())) {

            // 第一次访问该节点的时候
            zkClient.writeData(childrenPath, currentTime);
        } else {
            long time = currentTime - Long.parseLong(o.toString());
            if (time > 5000) {
                // 响应时间超过5秒，把值置为null
                zkClient.writeData(childrenPath, null);
            } else {
                zkClient.writeData(childrenPath, currentTime);
            }
        }

        System.out.println("服务器接收到的数据：" + msg);
        return "success";
    }
}
